package com.nanhai.buddhist.college.module.collegebase.service.studentroll;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nanhai.buddhist.college.framework.common.enums.UserTypeEnum;
import com.nanhai.buddhist.college.framework.common.pojo.CommonResult;
import com.nanhai.buddhist.college.framework.common.util.monitor.TracerUtils;
import com.nanhai.buddhist.college.framework.common.util.servlet.ServletUtils;
import com.nanhai.buddhist.college.module.collegebase.controller.teacher.teacher.vo.AuthLoginReqVO;
import com.nanhai.buddhist.college.module.collegebase.controller.teacher.teacher.vo.AuthLoginRespVO;
import com.nanhai.buddhist.college.module.collegebase.convert.teacherteachers.TeacherAuthConvert;
import com.nanhai.buddhist.college.module.collegebase.dal.dataobject.studentroll.StudentRollDO;
import com.nanhai.buddhist.college.module.collegebase.dal.dataobject.teacherteachers.TeacherTeachersDO;
import com.nanhai.buddhist.college.module.collegebase.dal.mysql.studentroll.StudentRollMapper;
import com.nanhai.buddhist.college.module.collegebase.dal.mysql.teacherteachers.TeacherTeachersMapper;
import com.nanhai.buddhist.college.module.system.api.logger.LoginLogApi;
import com.nanhai.buddhist.college.module.system.api.logger.dto.LoginLogCreateReqDTO;
import com.nanhai.buddhist.college.module.system.api.oauth2.OAuth2TokenApi;
import com.nanhai.buddhist.college.module.system.api.oauth2.dto.OAuth2AccessTokenCreateReqDTO;
import com.nanhai.buddhist.college.module.system.api.oauth2.dto.OAuth2AccessTokenRespDTO;
import com.nanhai.buddhist.college.module.system.enums.logger.LoginLogTypeEnum;
import com.nanhai.buddhist.college.module.system.enums.logger.LoginResultEnum;
import com.nanhai.buddhist.college.module.system.enums.oauth2.OAuth2ClientConstants;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;

import static com.nanhai.buddhist.college.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.nanhai.buddhist.college.module.system.enums.ErrorCodeConstants.AUTH_LOGIN_BAD_CREDENTIALS;

/**
 * @author AKai
 * @date 2022/8/24
 */
@Service
@Validated
public class StudentAuthServiceImpl implements  StudentAuthService {
    @Resource
    private LoginLogApi loginLogApi;

    @Resource
    private OAuth2TokenApi oAuth2TokenApi;

    @Resource
    private StudentRollMapper studentRollMapper;
    @Override
    public AuthLoginRespVO login(AuthLoginReqVO reqVO) {

        StudentRollDO authenticate = authenticate(reqVO.getUsername(), reqVO.getPassword());
        return createTokenAfterLoginSuccess(authenticate.getId(), reqVO.getUsername(), LoginLogTypeEnum.LOGIN_TEACHER);
    }



    private AuthLoginRespVO createTokenAfterLoginSuccess(String userId, String username, LoginLogTypeEnum logType) {
        // 插入登陆日志
//        createLoginLog(userId, username, logType, LoginResultEnum.SUCCESS);
        // 创建访问令牌

        OAuth2AccessTokenCreateReqDTO oAuth2AccessTokenCreateReqDTO = new OAuth2AccessTokenCreateReqDTO();
        oAuth2AccessTokenCreateReqDTO.setUserId(userId);
        oAuth2AccessTokenCreateReqDTO.setScopes(null);
        oAuth2AccessTokenCreateReqDTO.setClientId(OAuth2ClientConstants.CLIENT_ID_DEFAULT);
        oAuth2AccessTokenCreateReqDTO.setUserType(getUserType().getValue());
        CommonResult<OAuth2AccessTokenRespDTO> accessToken = oAuth2TokenApi.createAccessToken(oAuth2AccessTokenCreateReqDTO);
        return TeacherAuthConvert.INSTANCE.convert(accessToken.getData());
    }

    //    @Override
    private StudentRollDO authenticate(String username, String password) {
        final LoginLogTypeEnum logTypeEnum = LoginLogTypeEnum.LOGIN_TEACHER;
        // 校验账号是否存在
        StudentRollDO user = studentRollMapper.selectOne(new LambdaQueryWrapper<StudentRollDO>().eq(StudentRollDO::getStudentName,username));
        if (user == null) {
            createLoginLog(null, username, logTypeEnum, LoginResultEnum.BAD_CREDENTIALS);
            throw exception(AUTH_LOGIN_BAD_CREDENTIALS);
        }
//        if (!userService.isPasswordMatch(password, user.getPassword())) {
//            createLoginLog(user.getId(), username, logTypeEnum, LoginResultEnum.BAD_CREDENTIALS);
//            throw exception(AUTH_LOGIN_BAD_CREDENTIALS);
//        }
        // 校验是否禁用
//        if (ObjectUtil.notEqual(user.getStatus(), CommonStatusEnum.ENABLE.getStatus())) {
//            createLoginLog(user.getId(), username, logTypeEnum, LoginResultEnum.USER_DISABLED);
//            throw exception(AUTH_LOGIN_USER_DISABLED);
//        }
        return user;
    }

    private void createLoginLog(String userId, String username,
                                LoginLogTypeEnum logTypeEnum, LoginResultEnum loginResult) {
        // 插入登录日志
        LoginLogCreateReqDTO reqDTO = new LoginLogCreateReqDTO();
        reqDTO.setLogType(logTypeEnum.getType());
        reqDTO.setTraceId(TracerUtils.getTraceId());
        reqDTO.setUserId(userId);
        reqDTO.setUserType(getUserType().getValue());
        reqDTO.setUsername(username);
        reqDTO.setUserAgent(ServletUtils.getUserAgent());
        reqDTO.setUserIp(ServletUtils.getClientIP());
        reqDTO.setResult(loginResult.getResult());
        loginLogApi.createLoginLog(reqDTO);
        // 更新最后登录时间
//        if (userId != null && Objects.equals(LoginResultEnum.SUCCESS.getResult(), loginResult.getResult())) {
//            loginLogApi.updateUserLogin(userId, ServletUtils.getClientIP());
//        }
    }

    private UserTypeEnum getUserType() {
        return UserTypeEnum.TEACHER;
    }

}
